<template>
  <el-card class="section-card" shadow="never">
    <template #header>
      <div class="card-header">
        <span>语义检索</span>
        <el-button size="small" :loading="loading" @click="search">执行搜索</el-button>
      </div>
    </template>

    <el-form :model="form" label-position="top">
      <el-form-item label="关键词">
        <el-input v-model="form.query" placeholder="输入要检索的内容" clearable />
      </el-form-item>
      <el-form-item label="标签过滤">
        <el-select
          v-model="form.tags"
          multiple
          filterable
          allow-create
          placeholder="输入标签"
        >
          <el-option v-for="tag in docsTags" :key="tag" :label="tag" :value="tag" />
        </el-select>
      </el-form-item>
    </el-form>

    <el-empty description="暂无结果" v-if="!results.length && !loading" />

    <el-table
      v-else
      :data="results"
      border
      size="small"
      :row-class-name="rowClassName"
    >
      <el-table-column label="标题" prop="title" min-width="200" />
      <el-table-column label="匹配得分" width="120">
        <template #default="{ row }">
          <el-progress :percentage="Math.round((row.score || 0) * 100)" :stroke-width="10" />
        </template>
      </el-table-column>
      <el-table-column label="内容摘要" min-width="240">
        <template #default="{ row }">
          <span>{{ extractSummary(row.content) }}</span>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import { computed, reactive } from 'vue';
import { useDocsStore } from '@/stores/docs';

const docsStore = useDocsStore();

const form = reactive({
  query: '',
  tags: []
});

const results = computed(() => docsStore.searchResults);
const loading = computed(() => docsStore.loading);

const docsTags = computed(() => {
  const tags = new Set();
  docsStore.items.forEach((doc) => {
    (doc.metadata?.tags || []).forEach((tag) => tags.add(tag));
  });
  return [...tags];
});

async function search() {
  if (!form.query) return;
  await docsStore.searchByText(form.query, form.tags);
}

function extractSummary(content) {
  if (!content) return '';
  return content.length > 120 ? `${content.slice(0, 120)}...` : content;
}

function rowClassName({ rowIndex }) {
  return rowIndex % 2 === 0 ? 'is-even' : '';
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-table ::v-deep(.is-even) {
  background-color: #fafafa;
}
</style>
